package xyz.hubery.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.enums.ApiErrorCode;
import com.baomidou.mybatisplus.extension.exceptions.ApiException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;
import xyz.hubery.domain.SysMenu;
import xyz.hubery.feign.JwtToken;
import xyz.hubery.feign.OAuth2FeignClient;
import xyz.hubery.model.LoginResult;
import xyz.hubery.service.SysLoginService;
import xyz.hubery.service.SysMenuService;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class SysLoginServiceImpl implements SysLoginService {

    @Autowired
    private OAuth2FeignClient oAuth2FeignClient;

    @Autowired
    private SysMenuService sysMenuService;

    @Qualifier("redisTemplate")
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public LoginResult login(String username, String password) {
        // 1、获取token
        String basicToken = "Basic " + Base64Utils.encodeToString("coin-api:coin-secret".getBytes());
        ResponseEntity<JwtToken> response = oAuth2FeignClient.getToken("password", username, password, "admin_type", basicToken);
        if (response.getStatusCode() != HttpStatus.OK) {
            throw new ApiException(ApiErrorCode.FAILED);
        }
        JwtToken jwtToken = response.getBody();
        String token = jwtToken.getAccessToken();
        // 2、 获取用户菜单
        // 解析token，获取用户id
        Jwt jwt = JwtHelper.decode(token);
        String jwtClaims = jwt.getClaims();
        JSONObject jsonObject = JSON.parseObject(jwtClaims);
        Long id =Long.valueOf(jsonObject.getString("user_name"));
        // 根据用户id获取菜单
        List<SysMenu> menus = sysMenuService.getMenusByUserId(id);
        // 3、 获取权限列表
        List<SimpleGrantedAuthority> authorities = jsonObject.getJSONArray("authorities").stream().map(auth -> new SimpleGrantedAuthority(auth.toString())).collect(Collectors.toList());

        // 将token保存在redis缓存中（用于登出）
        redisTemplate.opsForValue().set(token,"",jwtToken.getExpiresIn(), TimeUnit.SECONDS);

        return new LoginResult(jwtToken.getTokenType() + " "+ token, menus, authorities);
    }
}
